package com.jn.common.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

    private static final String TAG = "DBHelper";
    private static final String DATABASE_NAME = "db_module";// 数据库名
    private static final int DATABASE_VERSION = 1;// 数据库版本号
    private static final String TABLE_NAME_USER = "user"; //用户表

    private static DBHelper mHelper = null;

    private DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //单例模式
    public static DBHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new DBHelper(context);
        }
        return mHelper;
    }

    //数据库创建时被调用
    @Override
    public void onCreate(SQLiteDatabase db) {
        initTable(db);
        initData(db);
    }

    //数据库升级
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 初始化数据表
     *
     * @param db 数据库
     */
    private void initTable(SQLiteDatabase db) {
        // 创建用户表
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME_USER + " (" +
                "_id integer primary key autoincrement," +
                "user_name text," +
                "login_state integer," +
                "money integer)");
    }

    /**
     * 初始化数据库内部模拟数据(仅在第一次安装时执行)
     *
     * @param db 数据库
     */
    private void initData(SQLiteDatabase db) {

    }

    public void login(String userName) {
        if (isUserExist(userName)) {
            updateLoginState(userName, true);
        } else {
            insertUser(userName, true, 0);
        }
    }

    public void insertUser(String userName, boolean loginState, int money) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("insert into " + TABLE_NAME_USER +
                " (user_name, login_state, money) " +
                "values" +
                "('" + userName + "'," + (loginState ? 1 : 0 )+ ", " + money + ")");
    }

    //添加用户
    public int insertUser2(String userName, boolean loginState, String money) {
        //获取可写数据库
        SQLiteDatabase db = getWritableDatabase();

        //创建ContentValues以Key-Value的形式封装数据
        ContentValues values = new ContentValues();
        values.put("user_name", userName);
        values.put("login_state", loginState ? 1 : 0);
        values.put("money", money);

        //执行insert方法，插入数据
        long newRowId = db.insert(TABLE_NAME_USER, null, values);
        Log.d(TAG, "insertUser2 newRowId = " + newRowId);
        return (int) newRowId;
    }

    //根据名字删除用户
    public void deleteUserByName(String name) {
        if (name != null) {
            SQLiteDatabase db = getReadableDatabase();
            int changedRowCount = db.delete(TABLE_NAME_USER, "user_name = ?", new String[]{name});
            Log.d(TAG, "deleteUserByName changedRowCount = " + changedRowCount);
        }
    }

    //根据用户名修改用户总额
    public void updateMoneyByName(String name, int money) {
        if (name != null) {
            SQLiteDatabase db = getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("money", money);
            int changedRowCount = db.update(TABLE_NAME_USER, values, "user_name = ?", new String[]{name});
            Log.d(TAG, "updateMoneyByName changedRowCount = " + changedRowCount);
        }
    }

    //根据用户名查理财总额
    @SuppressLint("Range")
    public int getMoneyByName(String userName) {
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(
                TABLE_NAME_USER,             // 表名
                null,                        // 要查询的列数据
                "user_name = ?",             // 条件语句
                new String[]{userName},      // 条件语句的值
                null,                        // group by
                null,                        // having
                null                         // 排序语句
        );
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                return cursor.getInt(cursor.getColumnIndex("money"));
            }
        }
        return 0;
    }

    @SuppressLint("Range")
    public String getLoginUser() {
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(
                TABLE_NAME_USER,             // 表名
                null,                        // 要查询的列数据
                "login_state = ?",           // 条件语句
                new String[]{"1"},           // 条件语句的值
                null,                        // group by
                null,                        // having
                null                         // 排序语句
        );
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                return cursor.getString(cursor.getColumnIndex("user_name"));
            }
        }

        return "";
    }

    //用户是否存在
    public boolean isUserExist(String userName) {
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(
                TABLE_NAME_USER,             // 表名
                null,                        // 要查询的列数据
                "user_name = ?",             // 条件语句
                new String[]{userName},      // 条件语句的值
                null,                        // group by
                null,                        // having
                null                         // 排序语句
        );
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                return true;
            }
        }
        return false;
    }

    public void updateLoginState(String userName, boolean loginState) {
        if (userName != null) {
            SQLiteDatabase db = getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("login_state", loginState ? 1 : 0);
            int changedRowCount = db.update(TABLE_NAME_USER, values, "user_name = ?", new String[]{userName});
            Log.d(TAG, "updateMoneyByName changedRowCount = " + changedRowCount);
        }
    }
}
